<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { marked } from 'marked'
import type { DashboardStat, DataSource, ReportTask } from '../types'
import Sidebar from '../components/Sidebar.vue'

const router = useRouter()

// 响应式状态
const stats = ref<DashboardStat[]>([])
const dataSources = ref<DataSource[]>([])
const reportTasks = ref<ReportTask[]>([])

// 数据源模态框
const isDataSourceModalOpen = ref(false)
const dataSourceModalError = ref('')
const initialDataSource: Partial<DataSource> = { id: undefined, name: '', type: 'CSV', status: '活跃' };
let activeDataSource = reactive({ ...initialDataSource });

// 报告模态框
const isReportModalOpen = ref(false)
const activeReport = ref<ReportTask | null>(null)
const reportContentHtml = computed(() => {
  if (activeReport.value && activeReport.value.content) {
    return marked(activeReport.value.content);
  }
  return '';
});

// 数据获取
const fetchDashboardData = async () => {
  try {
    const token = localStorage.getItem('token');
    const headers = { 'Authorization': `Bearer ${token}` };

    const [statsRes, dataSourcesRes, reportsRes] = await Promise.all([
      fetch('/api/stats', { headers }),
      fetch('/api/datasources', { headers }),
      fetch('/api/reports', { headers })
    ]);

    if (!statsRes.ok || !dataSourcesRes.ok || !reportsRes.ok) {
        throw new Error('Failed to fetch dashboard data');
    }

    stats.value = await statsRes.json();
    dataSources.value = await dataSourcesRes.json();
    reportTasks.value = await reportsRes.json();
  } catch (error) {
    console.error("Error fetching dashboard data:", error);
  }
};

onMounted(fetchDashboardData);

// 数据源模态框操作
const openAddModal = () => {
  Object.assign(activeDataSource, initialDataSource);
  isDataSourceModalOpen.value = true
  dataSourceModalError.value = ''
}

const openEditModal = (dataSource: DataSource) => {
  Object.assign(activeDataSource, dataSource);
  isDataSourceModalOpen.value = true
  dataSourceModalError.value = ''
}

const closeDataSourceModal = () => {
  isDataSourceModalOpen.value = false
}

// CRUD 操作
const saveDataSource = async () => {
  if (!activeDataSource.name?.trim()) {
    dataSourceModalError.value = '数据源名称是必填项。';
    return;
  }
  
  const isEditing = activeDataSource.id !== undefined;
  const url = isEditing ? `/api/datasources/${activeDataSource.id}` : '/api/datasources';
  const method = isEditing ? 'PUT' : 'POST';

  const body: any = { ...activeDataSource };
  if (!isEditing) {
    body.typeIcon = body.type === 'CSV' ? 'description' : (body.type === 'API' ? 'api' : 'storage');
    body.iconColor = body.type === 'CSV' ? 'text-green-500' : (body.type === 'API' ? 'text-purple-500' : 'text-blue-500');
    body.statusColor = body.status === '活跃' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';
  }

  try {
    const token = localStorage.getItem('token');
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      throw new Error('Failed to save data source');
    }

    await fetchDashboardData();
    closeDataSourceModal();
  } catch (error) {
    console.error(error);
    dataSourceModalError.value = '保存时发生错误。';
  }
};

const deleteDataSource = async (id: number) => {
  if (window.confirm('您确定要删除此数据源吗？')) {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`/api/datasources/${id}`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${token}` }
      });
      if (!response.ok) {
        throw new Error('Failed to delete data source');
      }
      await fetchDashboardData(); // 重新加载数据
    } catch (error) {
      console.error(error);
      alert('删除数据源失败。');
    }
  }
}

// 报告操作
const viewReport = async (id: number) => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/reports/${id}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    if (!response.ok) throw new Error('Failed to fetch report details.');
    activeReport.value = await response.json();
    isReportModalOpen.value = true;
  } catch (error) {
    console.error(error);
    alert('无法加载报告详情。');
  }
}

const downloadReport = (report: ReportTask) => {
  const blob = new Blob([report.content || ''], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `${report.name.replace(/\s/g, '_')}.md`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

const refreshReport = async (id: number) => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/reports/${id}/refresh`, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` }
    });
    if (!response.ok) throw new Error('Failed to start refresh.');
    
    // Optimistically update the UI
    const task = reportTasks.value.find((t: ReportTask) => t.id === id);
    if (task) {
      task.status = '处理中';
    }

    // Poll for completion
    setTimeout(() => {
        fetchDashboardData()
    }, 3500);

  } catch (error) {
    console.error(error);
    alert('刷新报告失败。');
  }
}

const closeReportModal = () => {
    isReportModalOpen.value = false;
    activeReport.value = null;
}


</script>

<template>
  <div class="dashboard-page bg-slate-50">
    <div class="relative flex size-full min-h-screen flex-col group/design-root overflow-x-hidden" style='font-family: Inter, "Noto Sans", sans-serif;'>
      <div class="flex h-full grow">
        <!-- 使用统一的侧边栏组件 -->
        <Sidebar />

        <!-- 主内容区域 -->
        <main class="ml-72 flex-1 p-8">
          <header class="mb-8">
            <h2 class="text-3xl font-bold tracking-tight text-[var(--text-primary)]">仪表盘</h2>
          </header>

          <!-- 统计卡片 -->
          <section class="grid grid-cols-1 gap-6 md:grid-cols-3 mb-8">
            <div v-for="stat in stats" :key="stat.label" class="flex flex-col gap-2 rounded-xl border border-[var(--border-color)] bg-white p-6 shadow-sm">
              <p class="text-base font-medium text-[var(--text-secondary)]">{{ stat.label }}</p>
              <p class="text-3xl font-bold text-[var(--text-primary)]">{{ stat.value }}</p>
            </div>
          </section>
            
          <!-- 数据源管理 -->
          <section class="mb-8">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-2xl font-semibold text-[var(--text-primary)]">我的数据源</h3>
              <button @click="openAddModal" class="flex items-center gap-2 rounded-lg bg-[var(--primary-color)] px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
                <span class="material-icons text-lg">add</span>
                添加数据源
              </button>
            </div>
            <div class="overflow-x-auto rounded-lg border border-[var(--border-color)] bg-white shadow-sm">
              <table class="min-w-full divide-y divide-[var(--border-color)]">
                <thead class="bg-slate-50">
                  <tr>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">名称</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">类型</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">状态</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">创建时间</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">操作</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-[var(--border-color)] bg-white">
                  <tr v-for="source in dataSources" :key="source.id">
                    <td class="whitespace-nowrap px-6 py-4 text-sm font-medium text-[var(--text-primary)]">{{ source.name }}</td>
                    <td class="whitespace-nowrap px-6 py-4 text-sm text-[var(--text-secondary)] flex items-center gap-2">
                      <span :class="['material-icons text-base', source.iconColor]">{{ source.typeIcon }}</span> {{ source.type }}
                    </td>
                    <td class="whitespace-nowrap px-6 py-4">
                      <span :class="['inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium', source.statusColor]">
                        <svg class="-ml-0.5 mr-1.5 h-2 w-2" :class="source.status === '活跃' ? 'text-green-400' : 'text-red-400'" fill="currentColor" viewBox="0 0 8 8">
                          <circle cx="4" cy="4" r="3"></circle>
                        </svg>
                        {{ source.status }}
                      </span>
                    </td>
                    <td class="whitespace-nowrap px-6 py-4 text-sm text-[var(--text-secondary)]">{{ source.created }}</td>
                    <td class="whitespace-nowrap px-6 py-4 text-sm font-medium">
                      <a @click="openEditModal(source)" class="text-[var(--primary-color)] hover:text-indigo-800 mr-3 cursor-pointer">编辑</a>
                      <a @click="deleteDataSource(source.id)" class="text-red-600 hover:text-red-800 cursor-pointer">删除</a>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </section>

          <!-- 报告任务管理 -->
          <section>
            <h3 class="text-2xl font-semibold text-[var(--text-primary)] mb-4">近期报表任务</h3>
            <div class="overflow-x-auto rounded-lg border border-[var(--border-color)] bg-white shadow-sm">
              <table class="min-w-full divide-y divide-[var(--border-color)]">
                <thead class="bg-slate-50">
                  <tr>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">报表名称</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">数据源</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">创建时间</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">耗时</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">状态</th>
                    <th class="px-6 py-3.5 text-left text-sm font-semibold text-[var(--text-primary)]" scope="col">操作</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-[var(--border-color)] bg-white">
                  <tr v-for="task in reportTasks" :key="task.id">
                    <td class="whitespace-nowrap px-6 py-4 text-sm font-medium text-[var(--text-primary)]">{{ task.name }}</td>
                    <td class="whitespace-nowrap px-6 py-4 text-sm text-[var(--text-secondary)]">{{ task.dataSource }}</td>
                    <td class="whitespace-nowrap px-6 py-4 text-sm text-[var(--text-secondary)]">{{ task.created }}</td>
                    <td class="whitespace-nowrap px-6 py-4 text-sm text-[var(--text-secondary)]">N/A</td>
                    <td class="whitespace-nowrap px-6 py-4">
                      <span :class="['inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium', task.status === '已完成' ? 'bg-green-100 text-green-800' : (task.status === '处理中' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800')]">
                        {{ task.status }}
                      </span>
                    </td>
                    <td class="whitespace-nowrap px-6 py-4 text-sm font-medium flex items-center gap-2">
                      <button @click="viewReport(task.id)" class="text-indigo-600 hover:text-indigo-800" title="查看报告"><span class="material-icons text-base">visibility</span></button>
                      <button @click="downloadReport(task)" class="text-green-600 hover:text-green-800" title="下载报告"><span class="material-icons text-base">download</span></button>
                      <button @click="refreshReport(task.id)" class="text-blue-600 hover:text-blue-800" title="刷新报告"><span class="material-icons text-base">refresh</span></button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </section>
        </main>
      </div>
    </div>

    <!-- 数据源模态框 -->
    <div v-if="isDataSourceModalOpen" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 transition-opacity">
      <div class="relative w-full max-w-lg rounded-xl border border-slate-200 bg-white p-8 shadow-lg">
        <h3 class="text-xl font-semibold text-slate-800 mb-6">{{ activeDataSource.id ? '编辑数据源' : '添加数据源' }}</h3>
        
        <form @submit.prevent="saveDataSource" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-slate-600 mb-1" for="source-name">名称</label>
            <input v-model="activeDataSource.name" id="source-name" type="text" class="block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm p-2.5" placeholder="例如：Q1 销售数据">
          </div>
          
          <div>
            <label class="block text-sm font-medium text-slate-600 mb-1" for="source-type">类型</label>
            <select v-model="activeDataSource.type" id="source-type" class="block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm p-2.5">
              <option>CSV</option>
              <option>PostgreSQL</option>
              <option>API</option>
            </select>
          </div>

           <div>
            <label class="block text-sm font-medium text-slate-600 mb-1" for="source-status">状态</label>
            <select v-model="activeDataSource.status" id="source-status" class="block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm p-2.5">
              <option>活跃</option>
              <option>停用</option>
            </select>
          </div>

          <div v-if="dataSourceModalError" class="text-sm text-red-600">{{ dataSourceModalError }}</div>
          
          <div class="flex justify-end gap-4 pt-4">
            <button @click="closeDataSourceModal" type="button" class="rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 shadow-sm hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">取消</button>
            <button type="submit" class="rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">保存</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 报告详情模态框 -->
    <div v-if="isReportModalOpen" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60" @click.self="closeReportModal">
        <div class="relative w-full max-w-3xl rounded-xl bg-white shadow-lg flex flex-col" style="max-height: 90vh;">
            <div class="flex items-center justify-between p-6 border-b border-slate-200">
                <h3 class="text-xl font-semibold text-slate-800">{{ activeReport?.name }}</h3>
                <button @click="closeReportModal" class="text-slate-500 hover:text-slate-800">
                    <span class="material-icons">close</span>
                </button>
            </div>
            <div class="p-6 overflow-y-auto">
              <article class="prose prose-slate max-w-none" v-html="reportContentHtml"></article>
            </div>
             <div class="flex justify-end p-4 bg-slate-50 border-t border-slate-200 rounded-b-xl">
                <button @click="activeReport && downloadReport(activeReport)" class="flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
                    <span class="material-icons text-base">download</span>
                    下载报告
                </button>
            </div>
        </div>
    </div>
  </div>
</template>

<style>
/* DashboardPage专用的CSS变量 - 全局作用域确保var()能正确解析 */
.dashboard-page {
  --primary-color: #4f46e5;
  --secondary-color: #f3f4f6;
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --border-color: #e5e7eb;
  --success-bg: #d1fae5;
  --success-text: #065f46;
  --warning-bg: #fef3c7;
  --warning-text: #92400e;
  --pending-bg: #fee2e2;
  --pending-text: #991b1b;
  --danger-bg: #fee2e2;
  --danger-text: #991b1b;
}

.dashboard-page .material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;
  line-height: 1;
  letter-spacing: normal;
  text-transform: none;
  display: inline-block;
  white-space: nowrap;
  word-wrap: normal;
  direction: ltr;
  -webkit-font-smoothing: antialiased;
}

.prose table {
  width: 100%;
  border-collapse: collapse;
}

.prose th,
.prose td {
  border: 1px solid #e5e7eb;
  padding: 0.5rem 1rem;
}

.prose thead {
  background-color: #f3f4f6;
}
</style>
